package coreDb

import (
	"strings"
	"time"

	"gitee.com/xgh2012/api-core/coreBiz"
	"github.com/redis/go-redis/v9"
)

// RedisConfigSentinel 哨兵模式配置
type RedisConfigSentinel struct {
	Hosts         []string // Sentinel 地址列表 ["ip:26379", ...]
	DB            int
	RedisPassword string // Master/Slave 密码
	SentinelPass  string // Sentinel requirepass，如果未设置则为空
	MasterName    string // sentinel monitor 的名字

	PoolSize     int
	MinIdleConns int
}

// InitSentinelRedis 初始化 Redis Sentinel 哨兵客户端
func InitSentinelRedis(cfg RedisConfigSentinel) (*redis.Client, error) {
	client := redis.NewFailoverClient(&redis.FailoverOptions{
		MasterName:       cfg.MasterName,
		SentinelAddrs:    cfg.Hosts,
		DB:               cfg.DB,
		Password:         cfg.RedisPassword, // Redis master/slave 的密码
		SentinelPassword: cfg.SentinelPass,  // 如果哨兵本身设置了 requirepass

		// 连接池配置
		PoolSize:     coreBiz.GetDefaultInt(cfg.PoolSize, 15),
		MinIdleConns: coreBiz.GetDefaultInt(cfg.MinIdleConns, 10),

		PoolTimeout:  3 * time.Second, // 获取连接超时
		ReadTimeout:  3 * time.Second,
		WriteTimeout: 3 * time.Second,
	})
	// 检查连接是否成功
	if err := pingRedis(client, strings.Join(cfg.Hosts, ","), cfg.DB); err != nil {
		return nil, err
	}
	return client, nil
}
